package com.yk.system.service.readImpl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yk.api.system.dto.CustomerInfoDTO;
import com.yk.common.core.domain.Result;
import com.yk.common.excel.core.CheckService;
import com.yk.system.convert.CustomerInfoConvert;
import com.yk.system.entity.CustomerInfo;
import com.yk.system.service.CustomerInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author lmx
 * @date 2023/12/28 10:20
 */
@Service
@RequiredArgsConstructor
public class CustomerInfoReadImpl implements CheckService<CustomerInfoDTO> {

    private final CustomerInfoService customerInfoService;
    private final CustomerInfoConvert customerInfoConvert;

    @Override
    public Result<CustomerInfoDTO> check(CustomerInfoDTO dto) {
        try{
            if (StrUtil.isEmpty(dto.getCompanyName())){
                return Result.fail("公司名不能为空");
            }
            if (StrUtil.isEmpty(dto.getContactPerson())){
                return Result.fail("联系人不能为空");
            }
            if (StrUtil.isNotEmpty(dto.getPhone()) && !Validator.isMobile(dto.getPhone())){
                return Result.fail("手机号格式不正确");
            }
            LambdaQueryWrapper<CustomerInfo> lambda = new LambdaQueryWrapper<>();
            lambda.eq(CustomerInfo::getCompanyName, dto.getCompanyName());
            long count = customerInfoService.count(lambda);
            if (count > 0) {
                return Result.fail("公司名已存在");
            }
            customerInfoService.save(customerInfoConvert.dto2Entity(dto));
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
}
